import telnetlib,time,sqlite3
def login():
  print tn.read_until("name:",1)
  for x in "root1":
    tn.write(x)
    tn.read_until(x,1)
  
  # tn.write("r")
  # tn.read_until("r",1)
  # tn.write("o")
  # tn.read_until("o",1)
  # tn.write("o")
  # tn.read_until("o",1)
  # tn.write("t")
  # tn.read_until("t",1)
  tn.write("\r\n")
  s=tn.read_until("assword:",1)
  if s.find("name is error,")>=0:
    return False
  for x in "admin":
    tn.write(x)
    tn.read_until("*",1)
  # tn.write("a")
  # tn.read_until("*",1)
  # tn.write("d")
  # tn.read_until("*",1)
  # tn.write("m")
  # tn.read_until("*",1)
  # tn.write("i")
  # tn.read_until("*",1)
  # tn.write("n")
  # tn.read_until("*",1)
  tn.write("\r\n")
  print tn.read_until("->",1)
  return True
def debug():
  tn.write("debug\r\n")
  print tn.read_until("assword:",1)
  for x in "ytnbx2008.":
    tn.write(x)
    tn.read_until("*",1)
  # tn.write("y")
  # tn.read_until("*",1)
  # tn.write("t")
  # tn.read_until("*",1)
  # tn.write("n")
  # tn.read_until("*",1)
  # tn.write("b")
  # tn.read_until("*",1)
  # tn.write("x")
  # tn.read_until("*",1)
  # tn.write("2")
  # tn.read_until("*",1)
  # tn.write("0")
  # tn.read_until("*",1)
  # tn.write("0")
  # tn.read_until("*",1)
  # tn.write("8")
  # tn.read_until("*",1)
  # tn.write(".")
  # tn.read_until("*",1)
  tn.write("\r\n")
  # tn.write("ytnbx2008.\r\n")
  print tn.read_until("DEBUG:->",1)
  return True
def checksnmpdown():
  tn.write(':show-task:tname="tSnmpd";\r\n')
  c=tn.read_until("DEBUG:->",1)
  print "start"
  if c.find("STOP")<>-1 and c.find("READY")<>-1:
    return True
  else:
    return False
def reboot():
  tn.write("reboot\r\n")
  print tn.read_until('Are you sure to reboot system?("Y" or Other)',5)
  tn.write("Y\r\n")
  return True
def saveconfig():
  tn.write(":save-config;\r\n")
  print tn.read_until("Succeed",5)

def telnetdo(HOST):
  # HOST="172.17.124.51"
  # USER="root"
  # PASS="admin"
  try:
    print "Connecting to "+HOST
    tn.open(HOST)
  except:
    print "Connect Error!"
    return
  if not login():
    return False
  debug()
  checksnmpdown()
  # conn.execute("update rnd set bSaved=1 where ndip='"+HOST+"'")
  # conn.commit()
  tn.close()

# conn=sqlite3.connect(r'lkt.db3')
# conn.text_factory = str
# nds=conn.execute("select ndip from rnd where snmp0<>'172.16.100.31' and bAlive=1").fetchall()
tn = telnetlib.Telnet()
telnetdo("172.17.124.51")
# for x in nds:
  # print x[0]
  # telnetdo(x[0])
del tn
# conn.close()
